import base64
import json
import re
import yaml

def parse_vmess_url(url):
    # 解码base64编码的vmess链接
    data = base64.b64decode(url.split('//')[1]).decode('utf-8')
    # 解析JSON数据
    vmess_info = json.loads(data)
    return vmess_info

def generate_vmess_template(vmess_info, name):
    # 生成vmess代理模板
    template = {
        "name": name,
        "type": "vmess",
        "server": vmess_info['add'],
        "port": int(vmess_info['port']),
        "uuid": vmess_info['id'],
        "alterId": int(vmess_info['aid']),
        "cipher": "auto",
        "network": vmess_info.get('net', 'tcp'),
        "ws-path": vmess_info.get('path', ""),
        "ws-headers": vmess_info.get('host', {})
    }
    return template

def read_vmess_file(file_path):
    with open(file_path, 'r') as file:
        vmess_links = file.readlines()
    return [link.strip() for link in vmess_links if link.strip()]

def generate_config_template(vmess_links):
    proxies = []
    proxy_groups = []
    rules = ["MATCH, RoundRobinGroup"]

    for i, link in enumerate(vmess_links):
        vmess_info = parse_vmess_url(link)
        name = f"🇺🇸美国{i+1}"  # 假设所有服务器都是美国的
        proxy_template = generate_vmess_template(vmess_info, name)
        proxies.append(proxy_template)
        proxy_groups.append(name)

    config = {
        "proxies": proxies,
        "proxy-groups": [
            {
                "name": "RoundRobinGroup",
                "type": "load-balance",
                "proxies": proxy_groups,
                "strategy": "round-robin",
                "url": "http://www.gstatic.com/generate_204",
                "interval": 300
            }
        ],
        "rules": rules
    }

    return config

def main():
    file_path = "20241230_vmess_Usa.txt"  # 替换为你的vmess文件路径
    vmess_links = read_vmess_file(file_path)
    config_template = generate_config_template(vmess_links)

    # 将生成的模板保存为YAML文件
    with open("config.yaml", 'w', encoding='utf-8') as yaml_file:
        yaml.dump(config_template, yaml_file, allow_unicode=True)

if __name__ == "__main__":
    main()